package com.zaoqi.service.impl;

import com.zaoqi.pojo.Device;
import com.zaoqi.repository.DeviceRepository;
import com.zaoqi.service.SensorService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
public class SensorServiceImpl implements SensorService {

    @Value("https://fbox360.com/api/v2/dmon/value/get?boxNo=300023040198") // 外部 API 地址，boxNo 固定
    private String externalApiUrl;

    private final RestTemplate restTemplate;
    private final DeviceRepository deviceRepository;

    public SensorServiceImpl(RestTemplate restTemplate, DeviceRepository deviceRepository) {
        // 为 RestTemplate 添加拦截器
        this.restTemplate = addRequestInterceptor(restTemplate);
        this.deviceRepository = deviceRepository;
    }

    @Override
    public List<Device> getDevicesBySerialNumbers(List<String> serialNumbers) {
        // 从数据库获取设备信息
        return deviceRepository.findBySerialNumberIn(serialNumbers);
    }

    @Override
    public List<Object> fetchSensorDataFromApi(List<String> ids) {
        try {
            // 获取 access_token
            String accessToken = fetchAccessToken();
            // 构造请求体，ids作为数组传递
            Map<String, Object> requestBody = Collections.singletonMap("ids", ids);
            // 设置请求头，Content-Type 为 application/json
            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json");
            headers.set("Authorization", "Bearer " + accessToken);
            // 构建请求体
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            // 发起POST请求
            ResponseEntity<List> response = restTemplate.exchange(
                    externalApiUrl,
                    HttpMethod.POST,
                    entity,
                    List.class
            );
            // 返回响应体
            return response.getBody();
        } catch (Exception e) {
            throw new RuntimeException("外部 API 调用失败：" + e.getMessage());
        }
    }

    // 获取 access_token 方法
    private String fetchAccessToken() {
        try {
            // 构造请求参数
            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("grant_type", "client_credentials");
            params.add("client_id", "68db2e8bda8d47b5b5db7eaf71c7dcdd");
            params.add("client_secret", "76dc724c95004acab25482d344dab407");
            params.add("scope", "fbox");

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/x-www-form-urlencoded");

            // 构建请求实体
            HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(params, headers);

            // 发起POST请求获取Token
            ResponseEntity<Map> response = restTemplate.exchange(
                    "https://fbox360.com/idserver/core/connect/token",
                    HttpMethod.POST,
                    entity,
                    Map.class
            );

            // 获取access_token
            Map<String, Object> body = response.getBody();
            if (body != null && body.containsKey("access_token")) {
                return body.get("access_token").toString();
            } else {
                throw new RuntimeException("获取 access_token 失败，响应数据：" + body);
            }
        } catch (Exception e) {
            throw new RuntimeException("调用 Token API 失败：" + e.getMessage());
        }
    }


    private RestTemplate addRequestInterceptor(RestTemplate restTemplate) {
        // 添加拦截器打印请求信息
        restTemplate.getInterceptors().add((request, body, execution) -> {
            System.out.println("Request URL: " + request.getURI());
            System.out.println("Request Method: " + request.getMethod());
            System.out.println("Request Headers: " + request.getHeaders());
            System.out.println("Request Body: " + new String(body));

            // 执行请求并返回响应
            return execution.execute(request, body);
        });
        return restTemplate;
    }
}
